package com.example.demo.service;

import com.example.demo.pojo.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;


@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    // 验证用户
    public User validateUser(String username, String password) {
        // 从数据库查询用户
        Optional<User> userOptional = userRepository.findByUsername(username);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            // 验证密码
            if (user.getPassword().equals(password)) {
                return user; // 验证成功，返回用户对象
            }
        }
        return null; // 验证失败，返回 null
    }

    // 保存用户信息
    public void saveUser(User user) {
        userRepository.save(user);
    }

    // 根据用户名查询用户
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}